package com.hopu.util;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

public class HBaseUtils {
    /*
    HBase工具类：
    //针对表的操作：HBaseAdmin
    创建表：
    判断表是否存：
    删除表
    //针对数据的操作：HTable
    插入数据（一次插入一列/多列）:一般分析一个功能，用户，年代的分析，浏览量（列族）、加入购物车统计、购买量统计
    查询数据（查询多个rowkey，指定的列族，下的所有的列）
    查询一个列族下所有rowkey对应的所有列的值。
    era  event_type   count
    50   view         116703
    50   view         116703
     */
    private static Configuration conf;
    private static Connection conn;

    static {
        conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "master:2181,slave1:2181,slave2:2181");
        try {
            conn = ConnectionFactory.createConnection(conf);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取操作DDL的客户端对象
     * @return
     * @throws IOException
     */
    private static HBaseAdmin getHBaseAdmin() throws IOException {
        return (HBaseAdmin) conn.getAdmin();
    }

    /**
     * 获取操作DML的HTable对象
     * @param tableName
     * @return
     * @throws IOException
     */
    private static HTable getHtable(String tableName) throws IOException {
        return (HTable) conn.getTable(TableName.valueOf(tableName));
    }

    /**
     * 判断指定的表是否存在
     * @param tableName
     * @return
     * @throws IOException
     */
    public static boolean tableExists(String tableName) throws IOException {
        return getHBaseAdmin().tableExists(tableName);
    }

    /**
     * 先查询指定的表是否存在，存在就删除该表
     * @param tableName
     * @throws IOException
     */
    public static void deleteTable(String tableName) throws IOException {
        HBaseAdmin client = getHBaseAdmin();
        if(tableExists(tableName)){
            client.disableTable(tableName);
            client.deleteTable(tableName);
        }
    }
    /**
     * 先判断HBase中是否有指定的表，有的话先删除，然后创建表
     * @param tableName ： 表名
     * @param familys ：列族的集合（数组）
     * @throws IOException
     */
    public static void createTable(String tableName, String... familys) throws IOException {
        HBaseAdmin client = getHBaseAdmin();
        //删除表
        deleteTable(tableName);
        //创建表
        HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf(tableName));
        for(String family : familys){
            tableDesc.addFamily(new HColumnDescriptor(family));
        }
        client.createTable(tableDesc);
        System.out.println(tableName + " 表创建成功");
    }

    /**
     * 添加一行结果（包含一个列族的多个列）到HBase
     * @param tableName 表名
     * @param rowkey
     * @param family 列族
     * @param colums 指定列族下所有列的名字
     * @param values 指定列族下所有列对应的值
     * @throws IOException
     */
    public static void putOneRowToHbase(String tableName, String rowkey, String family,
                                        String[] colums, String[] values) throws IOException {
        HTable table = getHtable(tableName);
        Put put = new Put(rowkey.getBytes());
        for(int i = 0; i < colums.length; i++){
            put.addColumn(Bytes.toBytes(family), Bytes.toBytes(colums[i]), Bytes.toBytes(values[i]));
        }
        table.put(put);
    }
    /**
     * 查询某张表，指定列族下所有列的值
     * @param tableName
     * @param family
     * @throws IOException
     */
    public static void scanByFamily(String tableName, String family) throws IOException {
        HTable table = getHtable(tableName);
        Scan scan = new Scan();
        scan.addFamily(family.getBytes());
        ResultScanner results = table.getScanner(scan);
        for (Result result : results){
            Cell[] cells = result.rawCells();
            for(Cell cell : cells){
                System.out.println(Bytes.toString(CellUtil.cloneValue(cell)));
            }
        }
    }

    public static void main(String[] args) throws IOException {

        scanByFamily("stus", "info1");

//        String[] columns = {"name", "sex", "age"};
//        String[] values = {"zs", "男", "18"};
//        String[] values1 = {"lisi", "女", "28"};
//        String[] values2 = {"wanwu", "男", "38"};
//        String[] values3 = {"zhaoliu", "女", "48"};
//        String[] values4 = {"zhuqi", "男", "58"};
//
//        putOneRowToHbase("stus", "1001", "info1", columns, values);
//        putOneRowToHbase("stus", "1002", "info1", columns, values1);
//        putOneRowToHbase("stus", "1003", "info1", columns, values2);
//        putOneRowToHbase("stus", "1004", "info1", columns, values3);
//        putOneRowToHbase("stus", "1005", "info1", columns, values4);

        //创建表
//        createTable("stus", "info1", "info2", "info3", "info4");

        //判断表是否存在
//        HBaseAdmin client = getHBaseAdmin();
//        boolean era = client.tableExists("era");
//        System.out.println(era);

//        //操作表
//        HTable table = getHtable("student");
//        //行键
//        Put put = new Put("1009".getBytes());
//        //列族:字段，数据
//        put.addColumn("info1".getBytes(), "name".getBytes(), "zyx".getBytes());
//        table.put(put);

    }

}
